package com.springboot.controller.web;

import com.springboot.model.DoctorAppointSet;
import com.springboot.service.DoctorAppointSetService;
import com.springboot.service.FileUploadService;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
public class UploadExcelController {
    @Autowired
    FileUploadService fileUploadService;

    @Autowired
    DoctorAppointSetService doctorAppointSetService;

    @RequestMapping(value = "/webuploadexcel")
    public String upLoadExcel(HttpServletRequest request, MultipartFile file, HttpServletResponse response)throws ServletException, IOException
    {
        String excelPath = "";
        String path = "Excel";
        try {
            excelPath=fileUploadService.uploadExcel(file,path);
            System.out.println("........");
            System.out.println(excelPath);
        }
        catch (Exception e)
        {
            System.out.println("UploadExcelController 出错");
            e.printStackTrace();
        }
        HttpSession session = request.getSession();
        session.setAttribute("excelPath",excelPath);
        Integer doctorId = (Integer)session.getAttribute("doctorId");

        System.out.println("开始读取excel");
        List<DoctorAppointSet> doctorAppointSets = parseExcel(excelPath);
        //把数据写入数据库
        for(int i=0;i<doctorAppointSets.size();i++)
        {
            DoctorAppointSet doctorAppointSet = doctorAppointSets.get(i);
            System.out.println(doctorAppointSet.toTestString());
        }

        System.out.println("医生设置可预约时间");
        try {
            for(int j=0;j<doctorAppointSets.size();j++)
            {
                DoctorAppointSet doctorAppointSet=doctorAppointSets.get(j);
                int morningNumber=doctorAppointSet.getMorningNum();
                int afternoonNumber=doctorAppointSet.getAfternoonNum();
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");//日期格式
                System.out.println(doctorId);
                //根据id查找该医生的可预约时间表
                ArrayList<DoctorAppointSet> doctorSets = doctorAppointSetService.findDoctorAppointById(doctorId);
                if(doctorSets.size()==0)
                {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    DoctorAppointSet set =new DoctorAppointSet();
                    set.setDoctorId(doctorId);
//                    set.setBookDate(sdf.parse(doctorAppointSet.getBookDate()));
                    set.setMorningNum(morningNumber);
                    set.setAfternoonNum(afternoonNumber);
                    doctorAppointSetService.insertDoctorAppoint(set);
                }
                else
                {
                    String []arrayDate=new String[doctorSets.size()+1];
                    Boolean isExist=false;
                    for (int i = 0; i < doctorSets.size(); i++)
                    {
                        DoctorAppointSet set=doctorSets.get(i);
                        String appointDate = format.format(set.getBookDate());
                        arrayDate[i]=appointDate;
                    }
                    for (int i = 0; i < doctorSets.size(); i++)
                    {
                        //如果该日期已经填过，则表示修改可预约时间
                        if (arrayDate[i].equals(doctorAppointSet.getBookDate()))
                        {
                            isExist=true;
                            break;
                        }
                    }
                    DoctorAppointSet appointSet=new DoctorAppointSet();
                    //如果该日期已经填过，则表示修改可预约时间
                    if(isExist)
                    {
                        appointSet.setDoctorId(doctorId);
//                        appointSet.setBookDate(doctorAppointSet.getBookDate());
                        appointSet.setMorningNum(morningNumber);
                        appointSet.setAfternoonNum(afternoonNumber);
                        doctorAppointSetService.updateDoctorSet(appointSet);
                    }
                    //如果该日期没有填过，则表示设置可预约时间
                    else
                    {
                        appointSet.setDoctorId(doctorId);
//                        appointSet.setBookDate(doctorAppointSet.getBookDate());
                        appointSet.setMorningNum(morningNumber);
                        appointSet.setAfternoonNum(afternoonNumber);
                        doctorAppointSetService.insertDoctorAppoint(appointSet);
                    }
                }
            }
        }catch (Exception e)
        {
            e.printStackTrace();
        }
        return "views/success.jsp";
    }

    @CrossOrigin
    @RequestMapping(value = "/writedatabase")
    @ResponseBody
    public String writeDataBase(HttpServletRequest request, HttpServletResponse response)
    {
//        HttpSession session = request.getSession();
//        String excelPath = (String)session.getAttribute("excelPath");
        //List<DoctorAppointSet> doctorAppointSets = parseExcel(excelPath);
        //把数据写入数据库
//        for(int i=0;i<doctorAppointSets.size();i++)
//        {
//            DoctorAppointSet doctorAppointSet = doctorAppointSets.get(i);
//            System.out.println(doctorAppointSet.toTestString());
//        }
        System.out.println("跳转页面");
        return "views/医生排班表.jsp";
    }



    // 解析Excel,读取内容,path Excel路径
    public static List<DoctorAppointSet> parseExcel(String path)
    {
        System.out.println("进入parseExcel函数");
        List<DoctorAppointSet> doctorAppointSets = new ArrayList<>();
        File file = null;
        InputStream input = null;
        if (path != null && path.length() > 7)
        {
            // 判断文件是否是Excel(2003、2007)
            String suffix = path.substring(path.lastIndexOf("."), path.length());
            file = new File(path);
            try {
                System.out.println("path:"+path);
                input = new FileInputStream(file);
            } catch (FileNotFoundException e) {
                System.out.println("未找到指定的文件！");
            }
            // Excel2003
            if (".xls".equals(suffix))
            {
                POIFSFileSystem fileSystem = null;
                // 工作簿
                HSSFWorkbook workBook = null;
                try {
                    fileSystem = new POIFSFileSystem(input);
                    workBook = new HSSFWorkbook(fileSystem);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                // 获取第一个工作簿
                HSSFSheet sheet = workBook.getSheetAt(0);
                doctorAppointSets = getContent((Sheet) sheet);
            }
            // Excel2007
            else if (".xlsx".equals(suffix))
            {
                XSSFWorkbook workBook = null;
                try {
                    workBook = new XSSFWorkbook(input);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                // 获取第一个工作簿
                XSSFSheet sheet = workBook.getSheetAt(0);
                doctorAppointSets = getContent(sheet);
            }
        }
        else {
            System.out.println("非法的文件路径!");
        }
        return doctorAppointSets;
    }

    // 获取Excel内容
    public static List<DoctorAppointSet> getContent(Sheet sheet)
    {
        List<DoctorAppointSet> doctorAppointSets= new ArrayList<>();
        // Excel数据总行数
        int rowCount = sheet.getPhysicalNumberOfRows();
        int cellCountAll = sheet.getRow(0).getPhysicalNumberOfCells();
        // 遍历数据行，略过标题行，从第二行开始
        for (int i = 1; i < rowCount; i++)
        {
            DoctorAppointSet doctorAppointSet=new DoctorAppointSet();
            Row row = sheet.getRow(i);
            // 遍历行单元格
            for (int j = 0; j < cellCountAll; j++)
            {
                Cell cell = row.getCell(j);
                if (cell == null)
                {
                    row.createCell(j).setCellValue("");
                }
                else {
                    // 根据cell中的类型来输出数据
                    switch (j)
                    {
                        case 0:
                            if (cell.getCellType() == CellType.NUMERIC) {
                                doctorAppointSet.setDoctorId((int) cell.getNumericCellValue());
                            }
                            break;
                        case 1:
                            if (cell.getCellStyle().getDataFormat() == 14) {
                                doctorAppointSet.setBookDate(cell.getDateCellValue());
                            }
                            break;
                        case 2:
                            if (cell.getCellType() == CellType.NUMERIC) {
                                doctorAppointSet.setMorningNum((int) cell.getNumericCellValue());
                            }
                            break;
                        case 3:
                            if (cell.getCellType() == CellType.NUMERIC) {
                                doctorAppointSet.setAfternoonNum((int) cell.getNumericCellValue());
                            }
                            break;
                        default:break;
                    }
                }
            }
            doctorAppointSets.add(doctorAppointSet);
        }
        return doctorAppointSets;
    }

}
